Ext.onReady(function() {
	Ext.define('UserModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'QUERYID', type:'string'},
            {name: 'ID', type:'string'},
            {name: 'USERNAME', type:'string'},
            {name: 'PWD', type:'string'},
            {name: 'USERGROUPIDS', type:'string'},
            {name: 'AVILIABLE', type:'bool'}
        ]
    });
	
	var userStore = Ext.create('Ext.data.Store',{
		model : 'UserModel'
	});
	
	var userGridRowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToMoveEditor: 1,
        autoCancel: true,
        listeners:{
        	  edit:{
        		  fn:userEdit
        	  }
          }
    });
	
	var userId = Ext.create('Ext.form.field.Text',{
        fieldLabel: str_usrmgr_usr,
        labelWidth: 40,
        width : 150
	});
	
	var userGroupStore = Ext.create('Ext.data.Store',{
		fields: [
	            { name: 'USERGROUPNAME', type: 'string'},
	            { name: 'USERGROUPID', type: 'string'}
	        ],
		 proxy:{
			type: 'ajax',
			url : getPath("/aa/po/userManager.do"),
			extraParams : {
            	"md":"readusergroup"
            },
			reader : {
				type : 'json',
				root : 'usergroup'
			}
		 }
	});
	
	var groupId = Ext.create('Ext.form.field.ComboBox',{
        typeAhead: true,
        triggerAction: 'all',
        selectOnTab: true,
        editable: true,
        displayField: 'USERGROUPNAME',
        valueField: 'USERGROUPID',
		store: userGroupStore,
        lazyRender: true,
        width:120
	});
	
	var userGrid = Ext.create('Ext.grid.Panel', {
		split: true,
		loadMask : true,
		store:userStore,
		border: false,
		plugins: [userGridRowEditing],
		columns: [
          {
              xtype: 'rownumberer',
              width: 30,
              hideable: false
          },
          {
        	  xtype: 'gridcolumn',
        	  text: str_usrmgr_usrid,
              width: 100,
              defaultWidth: 0,
              dataIndex: 'ID',
              hideable: false,
              editor : {
              }
          },
          {
        	  xtype: 'gridcolumn',
        	  text: str_usrmgr_uname,
              width: 100,
              defaultWidth: 0,
              dataIndex: 'USERNAME',
              hideable: false,
              editor : {
              }
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'PWD',
              text: str_usrmgr_pwd,
              width : 100,
              hideable: false,
              renderer : function(value, p, r) {return value ? '******' : '';},
              editor : {
            	  xtype: 'textfield',
            	  inputType: 'password'
              }
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'USERGROUPIDS',
              text: '&nbsp;&nbsp;' + str_grpmgr_usergroup,
              hideable: false,
              flex: 1,
              editor : {
            	  xtype: 'combobox',
                  typeAhead: true,
                  triggerAction: 'all',
                  selectOnTab: true,
                  editable: false,
                  displayField: 'USERGROUPNAME',
                  valueField: 'USERGROUPID',
                  multiSelect: true,
        		  store: userGroupStore,
                  lazyRender: true
              }
          },
          {
        	  xtype: 'booleancolumn',
              header: str_usrmgr_isaviliable,
              dataIndex: 'AVILIABLE',
              width: 60,
              editor: {
                  xtype: 'checkbox',
                  cls: 'x-grid-checkheader-editor'
              }
          },
          {

              xtype: 'actioncolumn',
              draggable: false,
              sortable: false,
              hideable: false,
              width: 30,
              items: [
                  {
                	  icon:getPath('/common/images/delete.png'),
                	  handler : function(grid, rowIndex, colIndex){
    					  var id = userStore.getAt(rowIndex).get('QUERYID');
                		  if (id != null && id != "") {
                			  Ext.MessageBox.confirm(str_common_confirm, str_common_confirmdel, function(button, text) {
                				  if(button == "yes") {
                					  Ext.Ajax.request({
            							  url : getPath('/aa/po/userManager.do'),
            							  params : {
            								  md : 'deleteUser',
            								  ID : id
            							  },
            							  actionMethods: 'POST',
            							  success : function(response) {  
            					            	var ret = Ext.JSON.decode(response.responseText);
            					            	if(ret.success){
            					            		userGridRowEditing.cancelEdit();
            			                			var sm = grid.getSelectionModel();
            			                			sm.select(rowIndex);
            			                			userStore.remove(sm.getSelection());
            					            	}
            					            	else {
            					            		Ext.MessageBox.alert(str_common_error,ret.msg);
            					            	}
            					          }
            						  });
                				  }
                			  });
                		  }
                		  else {
                			  userGridRowEditing.cancelEdit();
                			  var sm = grid.getSelectionModel();
                			  sm.select(rowIndex);
                			  userStore.remove(sm.getSelection());
                		  }
                	  }
                  }
              ]
          
          }
        ],
	    dockedItems: [
		  {
		      xtype: 'toolbar',
		      dock: 'top',
		      items: [
		          {
                      xtype: 'button',
                      iconCls: 'icon-add',
                      text: str_common_add,
                      listeners: {
                          click: {
                        	  fn:addUser
                          }
                      }
                  },
		          {
                      xtype: 'tbseparator'
                  },
                  userId,
                  {
                	  xtype: 'label',
                	  text: str_grpmgr_usergroup,
                	  width:50
                  },
                  groupId,
                  {
                	  xtype: 'button',
                	  text: str_common_query,
                	  listeners: {
                          click: {
                        	  fn:queryUser
                          }
                      }
                  }
		      ]
		   },
		]
	});
	
	function addUser(){
		userGridRowEditing.cancelEdit();
		var r = Ext.create('UserModel', {
			'ID': '',
            'USERNAME': '',
            'PWD': '',
            'MENUGROUPIDS': '',
            'AVILIABLE': true
        });
		userStore.insert(0, r);
		userGridRowEditing.startEdit(0, 0);
	}
	
	function queryUser(){
		userStore.setProxy({
			type : 'ajax',
			actionMethods: 'POST',
			url : getPath("/aa/po/userManager.do"),
			extraParams : {
            	"md":"readuser",
            	"USERID":userId.getRawValue(),
            	"GROUPID":groupId.value
            },
			reader : {
				type : 'json',
				root : 'user',
				totalProperty : 'totalCount'
			}
		});
		userStore.load();
	}
	
	function userEdit(editor, e){
		var oldId = e.record.data['QUERYID'];
		var newId = e.record.data['ID'];
		var userName = e.record.data['USERNAME'];
		var pwd = e.record.data['PWD'];
		var usergroups = e.record.data['USERGROUPIDS'];
		var aviliable = e.record.data['AVILIABLE'];
		if (!isBlank(oldId) && (oldId != newId)) {
			Ext.MessageBox.alert(str_common_warn,str_usrmgr_idchg);
			return false;
		}
		if(isBlank(newId)){
			Ext.MessageBox.alert(str_common_warn,str_usrmgr_idnull);
			return false;
		}
		if(isBlank(pwd)){
			Ext.MessageBox.alert(str_common_warn,str_usrmgr_pwdnull);
			return false;
		}
		if(isBlank(usergroups)){
			Ext.MessageBox.alert(str_common_warn,str_usrmgr_ugnull);
			return false;
		}
		Ext.Ajax.request({
            url : getPath("/aa/po/userManager.do"),
            method: 'POST',
            params : {
            	"md":"updateuser",
            	"QUERYID" : oldId,
                "ID" : newId,
                "USERNAME" : userName,
                "PWD" : pwd,
                "USERGROUPIDS" : usergroups,
                "AVILIABLE" : aviliable
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(ret.success){
                    e.record.data['QUERYID'] = ret.msg;
                    e.record.commit();
            	}
            	else {
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            }
        });
	}
	
	userGridWin = Ext.create('Ext.Window', {
		maximizable: true,
        title: str_usrmgr_usrmgr,
        height: 500,
        width: 600,
        iconCls: 'icon-edit-user',
        layout: 'fit',
        closeAction: 'hide',
        items: [userGrid],
        x: 10,
        y: 30,
        listeners:{
        	hide:function(){
        		if(userMgrBtn.pressed){
        			userMgrBtn.toggle();
        		}
        	}
        }
    });
});